package com.yuan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.volcengine.JSON;
import com.volcengine.ark.runtime.model.bot.completion.chat.BotChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionChoice;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import com.yuan.base.R;
import com.yuan.constant.GlobalConstant;
import com.yuan.entity.dao.ChatMsg;
import com.yuan.entity.dao.ChatSession;
import com.yuan.entity.param.ChatParam;
import com.yuan.entity.resp.ChatResultVo;
import com.yuan.service.ChatMsgService;
import com.yuan.service.ChatSessionService;
import com.yuan.service.DsService;
import com.yuan.subscriber.DsSubscriber;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class DsServiceImpl implements DsService {


    private final ChatSessionService chatSessionService;
    private final ChatMsgService chatMsgService;


    static String apiKey = "751f679c-6ab1-4cb4-af2e-d9c96209c48a";

    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service =
            ArkService.builder()
                    .dispatcher(dispatcher)
                    .connectionPool(connectionPool)
                    .apiKey(apiKey)
                    .build();


    /**
     * 根据输入的提示信息获取聊天响应的流式数据
     *
     * @param sessionId 输入的提示信息
     * @return 包含聊天响应的 Flux 流
     */
    Flux<String> getChatResponse(String sessionId , String botId) {
        // 创建聊天消息列表
        List<ChatMessage> messages = new ArrayList<>();
        // 创建用户角色的聊天消息并添加到列表中
        // 多轮对话，将历史对话加载到上下文
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setSessionId(sessionId);
        List<ChatMsg> list = chatMsgService.queryList(chatMsg);
        for (ChatMsg msgHistory : list) {
            if (msgHistory.getRole().equals(GlobalConstant.ROLE.USER)) {
                messages.add(ChatMessage.builder().role(ChatMessageRole.USER).content(msgHistory.getContent()).build());
            } else if (msgHistory.getRole().equals(GlobalConstant.ROLE.ASSISTANT)) {
                messages.add(ChatMessage.builder().role(ChatMessageRole.ASSISTANT).content(msgHistory.getContent()).build());
            }
        }
        //messages.add(ChatMessage.builder().role(ChatMessageRole.USER).content(prompt).build());
        //messages.add(ChatMessage.builder().role(ChatMessageRole.ASSISTANT).content(prompt).build());


        BotChatCompletionRequest streamChatCompletionRequest = BotChatCompletionRequest.builder()
                .botId(botId)
                .messages(messages)
                .stream(true)
                .build();

        return Flux.from(service.streamBotChatCompletion(streamChatCompletionRequest).map(choice -> {
            //System.out.println("原始数据:" + choice);
            ChatResultVo chatResultVo = new ChatResultVo();
            chatResultVo.setRole(GlobalConstant.ROLE.ASSISTANT);
            if (choice.getReferences() != null && !choice.getReferences().isEmpty()) {
                choice.getReferences().forEach(ref -> System.out.println(ref.getUrl()));
            }
            String content = "";
            if (!choice.getChoices().isEmpty()) {
                ChatCompletionChoice chatCompletionChoice = choice.getChoices().get(0);
                if (chatCompletionChoice.getMessage().getReasoningContent() != null) {
                    log.info(chatCompletionChoice.getMessage().getReasoningContent()); // 对于R1模型，输出reasoning content
                    content = chatCompletionChoice.getMessage().getReasoningContent();

                } else {
                    log.info(chatCompletionChoice.getMessage().getContent().toString());
                    content = chatCompletionChoice.getMessage().getContent().toString();
                }
                log.error(JSONObject.toJSONString(chatCompletionChoice));
                if (chatCompletionChoice.getFinishReason() != null) {
                    if ("stop".equals(chatCompletionChoice.getFinishReason())) {
                        // 标记结束对话
                        chatResultVo.setMessageStatus(true);
                        // TODO 看前端需不需要这个值，需要的话这里返沪一个值作为标记
                    }
                } else {
                    chatResultVo.setMessageStatus(false);
                }
                chatResultVo.setMessageId(choice.getId());
            }

            chatResultVo.setMessage(content);
            return JSONObject.toJSONString(chatResultVo);
        }));

    }

    @Override
    public Flux<String> sendChat(ChatParam chatParam) {

        // List<User> userList = userMapper.selectList(null);

        ChatSession queryEntity = new ChatSession();
        queryEntity.setDeviceId(chatParam.getDeviceId());
        queryEntity.setSessionId(chatParam.getSessionId());
        List<ChatSession> list = chatSessionService.queryList(queryEntity);
        if (list == null || list.isEmpty()) {
            queryEntity.setTitle(chatParam.getMessage());
            queryEntity.setCreateTime(new Date());
            chatSessionService.insertByEntity(queryEntity);
        } else {
            queryEntity = list.get(0);
        }


        // 基础
        String base = "bot-20250417132955-dc4jw";

        // 基础 + 联网
        String baseOnlineSearch = "bot-20250417163114-t8cn8";

        //深度思考
        String deepThinkingBot = "bot-20250416213610-n6csp";

        //深度思考 + 联网
        String onlineSearchBot = "bot-20250416112546-wrlbp";


        String botId;
        // 都没选就V3
        if (!chatParam.isOnlineSearch() && !chatParam.isDeepThinking()) {
            botId = base;
        } else if (chatParam.isDeepThinking() && !chatParam.isOnlineSearch()) {
            botId = deepThinkingBot;
        } else if (!chatParam.isDeepThinking()) {
            botId = baseOnlineSearch;
        } else {
            botId = onlineSearchBot;
        }


        //
        // 同时保存对话表
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setContent(chatParam.getMessage());
        chatMsg.setRole(GlobalConstant.ROLE.USER);
        chatMsg.setCreateTime(new Date());
        chatMsg.setDeepThinking(chatParam.isDeepThinking());
        chatMsg.setOnlineSearch(chatParam.isOnlineSearch());
        chatMsg.setSessionId(queryEntity.getSessionId());
        chatMsg.setBotId(botId);
        chatMsgService.insertByEntity(chatMsg);

        String sessionId = queryEntity.getSessionId();
        return Flux.create(emitter -> {
            DsSubscriber dsSubscriber = new DsSubscriber(emitter, this, sessionId, chatMsgService);
            Flux<String> openAiResponse = getChatResponse(sessionId, botId);
            openAiResponse.subscribe(dsSubscriber);
            emitter.onDispose(dsSubscriber);
        });
    }

    @Override
    public void completed(String response) {
        log.info("ds -> completed -> todo save db");
        System.out.println(response);
    }

    @Override
    public void fail(String sessionId) {
        log.info("ds -> fail -> todo save db");
    }

    @Override
    public R conversation(String sessionId) {
        ChatMsg chatMsg = new ChatMsg();
        chatMsg.setSessionId(sessionId);
        List<ChatMsg> list = chatMsgService.queryList(chatMsg);
        return R.ok(list);
    }

    @Override
    public R conversationHistory(String deviceId) {

        ChatSession queryEntity = new ChatSession();
        queryEntity.setDeviceId(deviceId);
        List<ChatSession> list = chatSessionService.queryList(queryEntity);
        return R.ok(list);
    }


}
